package com.dd.machine.main.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.dd.machine.base.app.MyApplication;
import com.dd.machine.base.paser.FastJsonUtils;
import com.dd.machine.greendao.gen.OrderFormDao;
import com.dd.machine.main.user.model.OrderForm;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;

import static com.dd.machine.base.net.URLManager.BUILDOEDER;

public class DelteDataService extends Service {
    private Context context;
    public static final String ACTION = "com.dd.machine.main.service.DelteDataService";
//    long difference = 30 * 24 * 60 * 60 * 1000;
    Long difference=(long) (30L*24L*60L*60L*1000L);
    OrderFormDao dao;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = getApplicationContext();
        dao = MyApplication.getInstances().getDaoSession().getOrderFormDao();
        new DelteDataService.DelteThread().start();
        return super.onStartCommand(intent, flags, startId);
    }

    class DelteThread extends Thread {
        @Override
        public void run() {
            Log.e("--system", "delte");
            delteOrSend();
        }
    }

    private void delteOrSend() {
        long current = System.currentTimeMillis();
        Log.e("-->现在的时间戳",current+"");
        List<OrderForm> orderFormList = dao.loadAll();
        Log.e("==删除之前的大小",orderFormList.size()+"");
        for (int i = 0; i < orderFormList.size(); i++) {
            long times = orderFormList.get(i).getCreateTime();
            Log.e("-->订单的时间戳",times+"");


            Log.e("-->30天的毫秒",difference+"");
            long cha = current - times;
            Log.e("-->两个相差的时间间隔",cha+"");
            if (cha > difference) {//计算距离当前时间30天以上的数据进行删除
                Log.e("---->","删除"+orderFormList.get(i).getId());
                dao.deleteByKey(orderFormList.get(i).getId());
            }
        }
        send();

    }

    //获取删除之后剩下的数据
    String sb = "";

    private void send() {
        List<OrderForm> orderFormList = dao.loadAll();
        Log.e("==删除之后的大小",orderFormList.size()+"");
        for (int i = 0; i < orderFormList.size(); i++) {
            OrderForm orderForm = orderFormList.get(i);
            Gson gson = new Gson();
            String goodsInfo = gson.toJson(orderForm);
            sb  = sb+goodsInfo + ",";
        }
        Log.e("---->send failed", "未上传成功的订单"+sb);
        if (orderFormList.size() > 0) {
            String oderString = "[" + sb.substring(0, sb.length() - 1) + "]";
            Log.e("---->send failed", "拼接好的订单数据"+oderString);
            submit(oderString);
        }else {
            Intent localIntnet = new Intent("DeleteService");
            LocalBroadcastManager.getInstance(context).sendBroadcast(localIntnet);
        }

    }

    private void submit(final String oderString) {
        OkHttpUtils.postString()
                .url(BUILDOEDER)
                .content(oderString)
                .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("===sendError", e.getMessage());
                        //请求服务器失败，缓存的数据依旧保存着

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("===sendResponse", response);
                        try {
                            JSONObject object = new JSONObject(response);
                            String result = object.optString("result");
                            if ("1".equals(result)) {//上传成功,删除本地缓存的订单数据
                                dao.deleteAll();

                            } else {//上传失败
                                //请求服务器失败，缓存的数据依旧保存着
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

        Intent localIntnet = new Intent("DeleteService");
        LocalBroadcastManager.getInstance(context).sendBroadcast(localIntnet);
    }



}
